package com.wangxiaonan.process.plugin.directive;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * SQL 执行指令
 *
 * @Author: wangxiaonan
 * @Date: 2019/2/28
 **/
public class SQLDirective implements TemplateDirectiveModel {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {

        if (!params.isEmpty()) {
            params.forEach((key, value) -> System.out.println(key + "====" + value));
        }

        if (loopVars.length != 0) {
            throw new TemplateModelException("This directive doesn't allow loop variables.");
        }

        if (body == null) {
            throw new RuntimeException("missing body");
        } else {

            body.render(new ExecuteSQLWriter(env.getOut()));
        }

    }

    private static class ExecuteSQLWriter extends Writer {

        private final Writer writer;

        public ExecuteSQLWriter(Writer writer) {
            this.writer = writer;
        }

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            String sql = String.valueOf(cbuf);

            // 验证sql是否有效
//            valid(sql);
            // 执行sql
//            execute(sql);
            // 返回数据
            writer.write("数据库返回的数据");
        }

        @Override
        public void flush() throws IOException {
            writer.flush();
        }

        @Override
        public void close() throws IOException {
            writer.close();
        }
    }
}
